package hot100.logos51To60;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author logos
 * date 2025/7/15 18:12
 * @version v1.0
 * @Package hot100.logos51To60
 */
public class logos58 {

    /**
     * 58. 组合总和
     * https://leetcode.cn/problems/combination-sum/description/?envType=study-plan-v2&envId=top-100-liked
     */

    class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);
            List<List<Integer>> ans = new ArrayList<>();
            dfs(candidates, 0, target, new ArrayList<>(), ans);
            return ans;
        }

        private void dfs(int[] nums, int i, int target, List<Integer> path, List<List<Integer>> ans) {
            if (target == 0) {
                ans.add(new ArrayList<>(path));
                return;
            }
            for (int j = i; j < nums.length; j++) {
                if (nums[j] > target) {
                    break;
                }
                path.add(nums[j]);
                dfs(nums, j, target - nums[j], path, ans);
                path.remove(path.size() - 1);
            }
        }
    }
}
